import pytest
from common.recordlog import logs
from base.apiutil import BaseRequest
import time
from common.InformationPush.main import pushmsg
from conf.operactionconfig import OperactionConfig

import pytest
from read_all_yaml import pytest_generate_tests  # 替换为你的实际模块路径


def pytest_configure(config):
    config.pluginmanager.register(pytest_generate_tests)


@pytest.fixture(scope='session', autouse=True)
def clean_yam_data():
    BaseRequest().clean_yaml()


@pytest.fixture(scope='function', autouse=True)
def scope_data():
    logs.info("---------接口测试开始---------")
    yield
    logs.info('---------接口测试结束----------')


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    在pytest终端输出自定义的测试统计信息，并发送钉钉消息
    
    Args:
        terminalreporter (pytest.TerminalReporter): pytest的终端报告对象
        exitstatus (int): pytest的退出状态码
        config (pytest.Config): pytest的配置对象
    
    Returns:
        None
    """
    # 获取测试运行的统计信息
    total = terminalreporter._numcollected
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    error = len(terminalreporter.stats.get('error', []))
    times = time.time() - terminalreporter._sessionstarttime
    now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # 在终端输出自定义信息
    terminalreporter.section('Custom Summary')
    terminalreporter.write_line(f'Total tests: {total}')
    terminalreporter.write_line(f'Passed tests: {passed}')
    terminalreporter.write_line(f'Failed tests: {failed}')
    terminalreporter.write_line(f'Skipped tests: {skipped}')
    terminalreporter.write_line(f'times: {times}')
    content = f"""
    各位同事大家好,现在是北京时间{now_time}\n
    接下来由我来为大家播报项目:AI智慧商城自动化接口测试数据\n
    总测试用例数:{total}\n
    测试通过用例:{passed}个\n
    测试失败用例:{failed}个\n
    测试异常用例:{error}个\n
    跳过执行用例:{skipped}个\n
    总耗时:{times}秒\n
    项目接口地址:{OperactionConfig().get_section_for_data('api_envi', 'host')}\n
    祝您天天开心,万事如意
    """
    pushmsg('Dingtalk', content)
